<?php
namespace app\admin\controller;
use app\admin\model\IndexTableModel;
use app\admin\model\JoinTableModel;
use think\Db;
use think\Request;

require_once (__DIR__.'/../../../vendor/ReidsLock.class.php');
class FacomplainController extends Controller
{

    /**
     * 短视频举报列表
     * User:@hang
     */
    public function index(Request $request)
    {
        $param = $request->param();
        $whehe = array();
        if (isset($param['j_member_id']) && !empty($param['j_member_id'])) {
            $whehe[] = ['b.member_id','=',$param['j_member_id']];
        }
        if (isset($param['j_me_uid']) && !empty($param['j_me_uid'])) {
            $whehe[] = ['b.me_uid|b.me_nick_name','like',"%{$param['j_me_uid']}%"];
        }
        if (isset($param['short_content']) && !empty($param['short_content'])) {
            $whehe[] = ['c.short_content','like',"%{$param['short_content']}%"];
        }
        if (isset($param['label_name']) && !empty($param['label_name'])) {
            $whehe[] = ['d.label_name','like',"%{$param['label_name']}%"];
        }
        if (isset($param['f_member_id']) && !empty($param['f_member_id'])) {
            $whehe[] = ['e.member_id','=',$param['f_member_id']];
        }
        if (isset($param['f_me_uid']) && !empty($param['f_me_uid'])) {
            $whehe[] = ['e.me_uid|e.me_nick_name','like',"%{$param['f_me_uid']}%"];
        }
        if (isset($param['complain_id']) && !empty($param['complain_id'])) {
            $whehe[] = ['a.complain_id','=',$param['complain_id']];
        }
        if (isset($param['is_real']) && $param['is_real'] != '') {
            $whehe[] = ['a.is_real','=',$param['is_real']];
        }
        $whehetime = '';
        if (isset($param['add_time']) && !empty($param['add_time'])) {
            $time_arr = explode(' - ', $param['add_time']);
            $start_time = strtotime($time_arr[0]);
            $end_time = strtotime($time_arr[1].'23:59:59');
            $whehetime = "a.add_time >= $start_time AND a.add_time <= $end_time";
        }
        $data = Db::table('fa_short_complain')//短视频投诉表
            ->alias('a')
            ->join("fa_member b",'a.member_id = b.member_id','LEFT')//举报者用户信息表
            ->join("fa_short_video c",'a.short_video_id = c.id','LEFT')//短视频信息表
            ->join("fa_label d",'c.label_id = d.id','LEFT')//短视频标签表
            ->join("fa_member e",'a.short_member_id = e.member_id','LEFT')//短视频发布者用户信息表
            ->join("fa_short_appeal f",'a.short_video_id = f.short_video_id','LEFT')//申诉表
            ->where($whehe)
            ->where($whehetime)
            ->field('a.*,b.me_uid as j_me_uid,b.me_nick_name as j_me_nick_name,b.me_phone as j_me_phone,c.short_content,c.cover_url,c.video_url,c.status as video_status,d.label_name as video_label_name,e.me_uid as f_me_uid,e.me_nick_name as f_me_nick_name,e.me_phone as f_me_phone,f.id as su_id')
            ->order('a.add_time desc')
            ->paginate($this->admin['per_page'],false,['query'=>request()->param()]);

        $IndexTableModel = New IndexTableModel();
        $data->each(function ($v, $k)use($IndexTableModel) {
            switch($v['video_status']){
                case '1': $v['video_status_word'] = '正常';break;
                case '2': $v['video_status_word'] = '封禁';break;
            }
            switch($v['is_real']){
                case '0': $v['is_real_word'] = '未处理';break;
                case '1': $v['is_real_word'] = '已处理（有效举报）';break;
                case '2': $v['is_real_word'] = '已处理（无效举报）';break;
            }
            if(empty($v['su_id'])){
                $v['su_id_word'] = '未申诉';
            }else{
                $v['su_id_word'] = '已申诉';
            }
            $v['add_time'] = date('Y-m-d H:i',$v['add_time']);
            $v['handle_time'] = empty($v['handle_time'])?'-':date('Y-m-d H:i',$v['handle_time']);
            $v['handle_content'] = empty($v['handle_content'])?'-':$v['handle_content'];
            $v['short_content_word'] = cutStr($v['short_content'],7);

            if(empty($v['complain_img'])){
                $v['complain_img_word'] = '无';
            }else{
                $v['complain_img_word'] = explode(',',$v['complain_img']);
            }
            return $v;
        });
        $complain_list = $IndexTableModel->getList('fa_short_complain_type',"`status` = 1","id as complain_id,name as complain_name",'id asc');
        //关键词，排序等赋值
        $this->assign($request->get());
        $this->assign([
            'data'  => $data,
            'page'  => $data->render(),
            'total' => $data->total(),
            'complain_list' => $complain_list,
        ]);
        return $this->fetch();
    }


    /**
     * 查看申诉
     * User:@hang
     */
    public function getappeal(Request $request)
    {
        $id = input('id');//被申诉的短视频作品ID
        $param = $request->param();
        $whehe = array();
        $whehe[] = ['short_video_id','=',$id];
        $data = Db::table('fa_short_appeal')
            ->field("*")
            ->order('add_time desc')
            ->where($whehe)
            ->paginate($this->admin['per_page'],false,['query'=>request()->param()]);

        $data->each(function ($v, $k)use($id) {
            $v['add_time'] = date('Y-m-d H:i',$v['add_time']);
            if(empty($v['imgstr'])){
                $v['imgstr_word'] = '无';
            }else{
                $v['imgstr_word'] = explode(',',$v['imgstr']);
            }
            return $v;
        });

        //关键词，排序等赋值
        $this->assign($request->get());
        $this->assign([
            'data'  => $data,
            'page'  => $data->render(),
            'total' => $data->total(),
            'id' => $id,
        ]);
        return $this->fetch();
    }


    /**
     * 判定为有效举报
     * User:@hang
     */
    public function effective($id)
    {
        $this->assign([
            'data' => $id,
        ]);
        return $this->fetch();
    }


    /**
     * 确认 判定为有效举报
     * User:@hang
     */
    public function actioneffective()
    {
        $id = input('id');
        $handle_content = input('handle_content');
        $handle_content = empty($handle_content)?'违规':$handle_content;
        $IndexTableModel = New IndexTableModel();
        $complaininfo = $IndexTableModel->getFind('fa_short_complain',"`id` = '{$id}'",'*');
        if(empty($complaininfo)){
            return admin_error('举报信息未查询到',URL_CLOSE_REFRESH);
        }
        if($complaininfo['is_real'] != 0){
            return admin_error('举报信息已经处理过，无需再次处理',URL_CLOSE_REFRESH);
        }
        //操作上锁
        $Redis_Lock  =  new \Redislock();
        $otc_sell_key  =  'lock:actioneffective'.$id;	// 定义锁标识
        $is_lock  =  $Redis_Lock->lock($otc_sell_key, 15);	// 获取锁
        //解锁失败
        if(!$is_lock){
            return admin_error('操作频繁，请稍后再试',URL_CLOSE_REFRESH);
        }
        $ctime = time();
        Db::startTrans();
        $complainRes = $IndexTableModel->editInfo('fa_short_complain',"`id` = '{$id}'",array('is_real'=>1,'handle_time'=>$ctime,'handle_content'=>$handle_content));
        if(empty($complainRes)){
            Db::rollback(); // 回滚事务
            $Redis_Lock->unlock($otc_sell_key);	//释放锁
            return admin_error('举报信息处理失败',URL_CLOSE_REFRESH);
        }

        $appealInfo = $IndexTableModel->getFind('fa_short_appeal',"`short_video_id` = '{$complaininfo['short_video_id']}'",'*');//有申诉
        if(!empty($appealInfo)){
            $IndexTableModel->editInfo('fa_short_appeal',"`short_video_id` = '{$complaininfo['short_video_id']}'",array('status'=>2,'handle_time'=>$ctime,'handle_content'=>$handle_content));
            //为被举报者添加通知
            $videoInfo = $IndexTableModel->getFind('fa_short_video',"`id` = '{$complaininfo['short_video_id']}'",'id,short_content');
            $short_content = !empty($videoInfo)?$videoInfo['short_content']:'-';
            $newRes = $IndexTableModel->addInfo('fa_news_system',array('type'=>4,'member_id'=>$complaininfo['member_id'],'j_member_id'=>$complaininfo['short_member_id'],'g_table'=>'fa_short_complain','g_id'=>$id,'content'=>'抱歉，您申诉的短视频作品《'.cutStr($short_content,7).'》未通过申诉，作品还继续为封禁状态，拒绝理由为【'.$handle_content.'】。','is_read'=>0,'add_time'=>$ctime));
            if(empty($newRes)){
                Db::rollback(); // 回滚事务
                $Redis_Lock->unlock($otc_sell_key);	//释放锁
                return admin_error('为被举报者添加系统通知失败',URL_CLOSE_REFRESH);
            }
        }
        $IndexTableModel->editInfo('fa_short_video',"`id` = '{$complaininfo['short_video_id']}'",array('status'=>2,'is_show'=>2));

        Db::commit();
        $Redis_Lock->unlock($otc_sell_key);	//释放锁
        return admin_success('操作成功',URL_CLOSE_REFRESH);
    }


    /**
     * 判定为无效举报
     * User:@hang
     */
    public function invalid($id)
    {
        $this->assign([
            'data' => $id,
        ]);
        return $this->fetch();
    }


    /**
     * 确定判定为无效举报
     * User:@hang
     */
    public function actioninvalid()
    {
        $id = input('id');
        $handle_content = input('handle_content');
        $handle_content = empty($handle_content)?'未违规':$handle_content;
        $IndexTableModel = New IndexTableModel();
        $complaininfo = $IndexTableModel->getFind('fa_short_complain',"`id` = '{$id}'",'*');
        if(empty($complaininfo)){
            return admin_error('举报信息未查询到',URL_CLOSE_REFRESH);
        }
        if($complaininfo['is_real'] != 0){
            return admin_error('举报信息已经处理过，无需再次处理',URL_CLOSE_REFRESH);
        }
        //操作上锁
        $Redis_Lock  =  new \Redislock();
        $otc_sell_key  =  'lock:actioninvalid'.$id;	// 定义锁标识
        $is_lock  =  $Redis_Lock->lock($otc_sell_key, 15);	// 获取锁
        //解锁失败
        if(!$is_lock){
            return admin_error('操作频繁，请稍后再试',URL_CLOSE_REFRESH);
        }
        $ctime = time();
        Db::startTrans();
        $complainRes = $IndexTableModel->editInfo('fa_short_complain',"`id` = '{$id}'",array('is_real'=>2,'handle_time'=>$ctime,'handle_content'=>$handle_content));
        if(empty($complainRes)){
            Db::rollback(); // 回滚事务
            $Redis_Lock->unlock($otc_sell_key);	//释放锁
            return admin_error('举报信息处理失败',URL_CLOSE_REFRESH);
        }

        $appealInfo = $IndexTableModel->getFind('fa_short_appeal',"`short_video_id` = '{$complaininfo['short_video_id']}'",'*');//有申诉
        if(!empty($appealInfo)){
            $IndexTableModel->editInfo('fa_short_appeal',"`short_video_id` = '{$complaininfo['short_video_id']}'",array('status'=>1,'handle_time'=>$ctime,'handle_content'=>$handle_content));
            //为被举报者添加通知
            $videoInfo = $IndexTableModel->getFind('fa_short_video',"`id` = '{$complaininfo['short_video_id']}'",'id,short_content');
            $short_content = !empty($videoInfo)?$videoInfo['short_content']:'-';
            $newRes = $IndexTableModel->addInfo('fa_news_system',array('type'=>3,'member_id'=>$complaininfo['member_id'],'j_member_id'=>$complaininfo['short_member_id'],'g_table'=>'fa_short_complain','g_id'=>$id,'content'=>'恭喜，您申诉的短视频作品《'.cutStr($short_content,7).'》申诉已通过，作品恢复为正常状态，通过理由为【'.$handle_content.'】。','is_read'=>0,'add_time'=>$ctime));
            if(empty($newRes)){
                Db::rollback(); // 回滚事务
                $Redis_Lock->unlock($otc_sell_key);	//释放锁
                return admin_error('为被举报者添加系统通知失败',URL_CLOSE_REFRESH);
            }
        }
        $IndexTableModel->editInfo('fa_short_video',"`id` = '{$complaininfo['short_video_id']}'",array('status'=>1,'is_show'=>1));

        Db::commit();
        $Redis_Lock->unlock($otc_sell_key);	//释放锁
        return admin_success('操作成功',URL_CLOSE_REFRESH);
    }



}
